﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Windows.Forms;

namespace TscMon
{   
    class TscProcessMon
    {
        #region Constants
        const string PROCESS_NAME = "tsc";
        const int UPDATE_INTERVAL = 100;
        #endregion

        #region Private fields
        private Process[] p;        
        private Timer t;
        private bool isDisabled = false;
        #endregion

        public TscProcessMon()
        {
            t = new Timer();
            t.Interval = UPDATE_INTERVAL;
            t.Tick += t_Tick;
            Refresh();
            t.Start();            
        }

        #region Events
        public event CountUpdatedDelegate CountUpdated;
        public delegate void CountUpdatedDelegate(object sender, CountUpdatedEventArgs newCount);
        public class CountUpdatedEventArgs
        {
            private int _newCount;
            public int NewCount 
            {
                get
                {
                    return this._newCount;
                }
            }

            public CountUpdatedEventArgs(int newCount)
            {
                this._newCount = newCount;
            }
        }
        #endregion

        #region Public properties
        public int Count
        {
            get
            {
                return p == null ? 0 : p.Length;
            }
        }

        public bool Enabled
        {
            get
            {
                return !this.isDisabled;
            }
        }
        #endregion

        #region Public methods
        public void Enable()
        {
            if (!isDisabled) return;
            
            isDisabled = false;
            t.Start();
        }

        public void Disable()
        {
            if (isDisabled) return;

            isDisabled = true;
            t.Stop();
        }
        #endregion

        #region Private methods
        private void t_Tick(object sender, EventArgs e)
        {
            Refresh();
        }

        private void Refresh()
        {
            if (CountUpdated == null) return;

            int oldCount = Count;
            p = Process.GetProcessesByName(PROCESS_NAME);

            if (!isDisabled && oldCount != Count)
            {
                CountUpdated(this, new CountUpdatedEventArgs(Count));
            }
        }
        #endregion
    }
}
